package com.smarthouse.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.smarthouse.model.IdCardDetectResponse;
import com.smarthouse.model.ExpectedInfo;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Service
public class IdCardService {
    private static final Logger logger = LoggerFactory.getLogger(IdCardService.class);

    private static final String API_KEY = "vx9uUcqyOuzyI2dkOmyn7vCn";
    private static final String SECRET_KEY = "fG2vyWqkATo4LX7tWfTMaauKr6SG3FqC";
    private String accessToken;

    // 预设的验证信息
    private static final String EXPECTED_NAME = "韦小宝";
    private static final String EXPECTED_NATIONALITY = "汉";
    private static final String EXPECTED_ADDRESS = "北京市东城区景山前街4号紫禁城敬事房";

    public IdCardDetectResponse detectIdCard(String image1Base64) throws Exception {
        // 获取access token
        if (accessToken == null) {
            accessToken = getAccessToken();
        }

        // 构建表单数据
        StringBuilder formData = new StringBuilder();
        formData.append("id_card_side=front");
        formData.append("&image=").append(URLEncoder.encode(image1Base64, StandardCharsets.UTF_8));
        formData.append("&detect_direction=true");
        formData.append("&detect_risk=true");
        formData.append("&detect_quality=false");
        formData.append("&detect_photo=false");
        formData.append("&detect_card=false");
        formData.append("&detect_ps=true");

        logger.info("请求参数: {}", formData);

        // 发送请求到百度API
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(
            MediaType.parse("application/x-www-form-urlencoded"), 
            formData.toString()
        );

        Request request = new Request.Builder()
            .url("https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + accessToken)
            .post(body)
            .addHeader("Content-Type", "application/x-www-form-urlencoded")
            .build();

        try (Response response = client.newCall(request).execute()) {
            String responseBody = response.body().string();
            logger.info("百度API响应: {}", responseBody);
            
            JSONObject result = JSON.parseObject(responseBody);
            
            // 首先检查是否有错误码
            if (result.containsKey("error_code") && result.getInteger("error_code") != 0) {
                String errorMsg = result.getString("error_msg");
                throw new RuntimeException("百度API错误: " + (errorMsg != null ? errorMsg : "未知错误"));
            }
            
            // 获取识别结果
            JSONObject wordsResult = result.getJSONObject("words_result");
            if (wordsResult == null) {
                throw new RuntimeException("识别结果为空，请确保图片清晰完整");
            }

            // 检查必要字段是否存在
            if (!wordsResult.containsKey("姓名") || !wordsResult.containsKey("民族") || !wordsResult.containsKey("住址")) {
                throw new RuntimeException("身份证信息不完整，缺少必要字段");
            }

            // 创建新的 JSONObject 来存储转换后的数据
            JSONObject convertedWordsResult = new JSONObject();
            
            // 安全地获取并转换字段
            JSONObject nameObj = wordsResult.getJSONObject("姓名");
            JSONObject nationalityObj = wordsResult.getJSONObject("民族");
            JSONObject addressObj = wordsResult.getJSONObject("住址");

            if (nameObj == null || nationalityObj == null || addressObj == null) {
                throw new RuntimeException("身份证字段格式错误");
            }

            // 转换字段名称
            convertedWordsResult.put("name", nameObj);
            convertedWordsResult.put("nationality", nationalityObj);
            convertedWordsResult.put("address", addressObj);

            // 提取身份证信息用于验证
            String name = nameObj.getString("words");
            String nationality = nationalityObj.getString("words");
            String address = addressObj.getString("words");

            if (name == null || nationality == null || address == null) {
                throw new RuntimeException("身份证字段内容为空");
            }

            logger.info("识别结果 - 姓名: {}, 民族: {}, 住址: {}", name, nationality, address);

            // 验证身份信息
            boolean nameMatch = EXPECTED_NAME.equals(name);
            boolean nationalityMatch = EXPECTED_NATIONALITY.equals(nationality);
            boolean addressMatch = EXPECTED_ADDRESS.equals(address);

            // 创建预期信息对象
            ExpectedInfo expectedInfo = new ExpectedInfo(
                EXPECTED_NAME,
                EXPECTED_NATIONALITY,
                EXPECTED_ADDRESS
            );

            if (nameMatch && nationalityMatch && addressMatch) {
                return new IdCardDetectResponse(
                    convertedWordsResult,
                    result.getString("image_status"),
                    "验证通过：欢迎回来，韦公公！",
                    expectedInfo
                );
            } else {
                StringBuilder errorMsg = new StringBuilder("身份验证失败: ");
                if (!nameMatch) errorMsg.append("姓名不匹配；");
                if (!nationalityMatch) errorMsg.append("民族不匹配；");
                if (!addressMatch) errorMsg.append("住址不匹配；");

                return new IdCardDetectResponse(
                    convertedWordsResult,
                    result.getString("image_status"),
                    errorMsg.toString(),
                    expectedInfo
                );
            }
        }
    }

    private String getAccessToken() throws Exception {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
            .url("https://aip.baidubce.com/oauth/2.0/token?" +
                "grant_type=client_credentials&" +
                "client_id=" + API_KEY + "&" +
                "client_secret=" + SECRET_KEY)
            .post(RequestBody.create(null, new byte[0]))
            .build();

        try (Response response = client.newCall(request).execute()) {
            String responseBody = response.body().string();
            logger.info("获取token响应: {}", responseBody);
            
            JSONObject result = JSON.parseObject(responseBody);
            String token = result.getString("access_token");
            if (token == null || token.isEmpty()) {
                throw new RuntimeException("获取access token失败");
            }
            return token;
        }
    }
} 